<template>
    <div class="guide-manage-wrapper">
        <!-- <Button class="md-add-jh" @click="showModal">创建指导书</Button> -->
        <Modal
            v-model="modal"
            width="1000"
            :mask-closable="false"
            title="编辑指导书"
            class="fix-height-modal"
        >
            <template v-if="data.templateid !== 'markdown'">
                <Steps :current="step" class="guide-step">
                    <Step title="基本信息"></Step>
                    <Step title="段落信息"></Step>
                </Steps>
                <Form
                    v-if="step === 0"
                    ref="creatGuideFormValidate"
                    :model="creatGuideFormValidate"
                    :rules="creatGuideRuleValidate"
                    :label-width="60"
                >
                    <FormItem label="名称" prop="name">
                        <Input
                            v-model.trim="creatGuideFormValidate.name"
                            placeholder='指导书名称长度为1-64个字符,名称中不能包含 \ : * ? " < > | ; , + =等特殊字符'
                            style="width:50%"
                        ></Input>
                    </FormItem>
                    <!-- <FormItem label="可见范围" prop="ispublic">
                    <RadioGroup v-model="creatGuideFormValidate.ispublic">
                        <Radio label="1">单位</Radio>
                        <Radio label="0">个人</Radio>
                    </RadioGroup>
                    <span v-if="!isCreate" style="color:#f90;display: inline-block;">
                        <Icon
                            type="ios-information-circle"
                        />可见范围由个人编辑为单位时，指导书使用的个人资源(图片，题目)的可见范围将变为单位</span
                    >
                </FormItem> -->
                </Form>
                <Section
                    v-if="step === 1"
                    :guideId="creatGuideFormValidate.id"
                    :guideName="creatGuideFormValidate.name"
                    @on-success="getSectionData"
                ></Section>
                <template slot="footer">
                    <Button @click="closeModal">取消</Button>
                    <Button type="primary" @click="switchStep"
                        ><template v-if="step === 0">下一步</template
                        ><template v-else>上一步</template></Button
                    >
                    <Button type="primary" @click="confirmGuide" v-if="step === 1">确定</Button>
                </template>
            </template>
            <template v-else
                ><EditMd
                    ref="editMd"
                    :guideId="data.guidbookid"
                    :guideName="data.guidbookname"
                ></EditMd>
                <template slot="footer">
                    <Button @click="closeModal">取消</Button>
                    <Button type="primary" @click="confirmGuide">确定</Button>
                </template></template
            >
        </Modal>
    </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import Section from './section';
import { creatGuide, modifyGuide, modifySection } from '@/api/guide.js';
import EditMd from './edit-md.vue';
export default {
    name: 'CreatModal',
    props: {
        value: {
            type: Boolean,
            default: false
        },
        data: {
            type: Object,
            default: () => {
                return {
                    id: '',
                    templateid: ''
                };
            }
        },
        type: {
            type: String,
            default: false,
            validator(value) {
                return ['add', 'update'].includes(value);
            }
        }
    },
    components: { Section, EditMd },
    data() {
        const validateName = (rule, value, callback) => {
            var reg = /[\\\:：*?？"”<>|;；，,+=]/gi;
            //验证警戒值
            if (value) {
                if (reg.test(value)) {
                    callback(new Error('名称不能包含下列任意字符 \\ : * ? " < > | ; , + ='));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        return {
            USER_ID: '',
            isRootDesinger: false,
            modal: this.value || false,
            step: 0,
            creatGuideFormValidate: {
                name: '',
                ispublic: '0'
            },
            isCreate: this.type === 'add' ? true : false,
            creatGuideRuleValidate: {
                name: [
                    {
                        required: true,
                        max: 64,
                        message: '指导书名称长度为1—64个字符',
                        trigger: 'change'
                    },
                    { validator: validateName, trigger: 'change' }
                ],
                ispublic: [{ required: true, message: '请选择可见范围', trigger: 'change' }]
            },
            sectionList: [] //段落列表
        };
    },
    watch: {
        modal: function(val) {
            if (!val) {
                this.$emit('input', false);
                this.$emit('close');
            }
        },
        value(val) {
            if (val) {
                this.showModal();
            } else {
                this.modal = val;
            }
        }
    },
    created() {
        // 获取用户id
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.isRootDesinger = November.isRootDesinger;
    },
    mounted() {},
    methods: {
        showModal() {
            this.modal = true;
            this.step = 0;
            this.creatGuideFormValidate = Object.assign({}, this.data, {
                name: this.data.guidbookname,
                id: this.data.guidbookid
            });
        },
        closeModal() {
            this.modal = false;
        },
        switchStep() {
            if (this.step === 0) {
                this.submitBtn('creatGuideFormValidate');
            } else {
                this.step = 0;
            }
        },
        // 提交按钮
        submitBtn(name) {
            if (this.type === 'add') {
                this.creatGuideHandleSubmit(name);
            } else {
                this.modifySubmit(name);
            }
        },
        creatGuideHandleSubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let formData = {};
                    formData.guidbookname = this.creatGuideFormValidate.name;
                    formData.ispublic = parseInt(this.creatGuideFormValidate.ispublic);
                    formData.templateid = this.USER_ID;
                    formData.createtime = '';
                    formData.designer = this.USER_ID;
                    formData.createuser = '';
                    creatGuide(formData)
                        .then((data) => {
                            if (data.code == 1) {
                                this.creatGuideFormValidate = data.attribute.data;
                                this.creatGuideFormValidate.id = data.attribute.data.guidbookid;
                                this.creatGuideFormValidate.name = data.attribute.data.guidbookname;
                                this.step = 1;
                                // this.createGuideModal = false;
                                //this.getGuideList();
                                // this.refreshFile();
                                // this.$Message.success('创建成功！');
                            } else {
                                this.$Message.error({
                                    content: data.message,
                                    duration: 3
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    this.$Message.error('请完善信息！');
                }
            });
        },
        modifySubmit(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    let formData = {};
                    formData.guidbookname = this.creatGuideFormValidate.name;
                    formData.ispublic = parseInt(this.creatGuideFormValidate.ispublic);
                    modifyGuide(this.creatGuideFormValidate.id, formData)
                        .then((data) => {
                            if (data.code == 1) {
                                this.step = 1;
                                // this.creatGuideFormValidate.id = data.atribute.data.guidbookid;
                                // this.$Message.success('编辑成功！');
                                // this.createGuideModal = false;
                                // this.getGuideList();
                            } else {
                                this.$Message.error('编辑失败！');
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    this.$Message.error('请完善信息！');
                }
            });
        },
        getSectionData(sectionList) {
            this.sectionList = sectionList;
        },
        confirmGuide() {
            if (this.data.templateid !== 'markdown') {
                if (this.sectionList.length === 0) {
                    this.$Message.info('请至少创建一个章节');
                } else {
                    this.modal = false;
                }
            } else {
                let currentGuide = this.$refs['editMd'].currentGuide;
                let currentGuideContent = this.$refs['editMd'].currentGuideContent;
                this.saveBtnD(currentGuide, currentGuideContent);
            }
        },
        saveBtnD(currentGuide, currentGuideContent) {
            let params = { ...currentGuide };
            params.sectiontext = currentGuideContent;
            if (!params.sectiontext) {
                this.$Message.info('指导书内容不能为空');
                return;
            }
            modifySection(params, params.sectionid).then((res) => {
                if (res.code == 1) {
                    this.$Message.success({
                        content: '编辑成功！',
                        duration: 3
                    });
                    this.modal = false;
                } else {
                    this.$Message.error({
                        content: res.message,
                        duration: 3
                    });
                }
            });
        }
    }
};
</script>
<style scoped>
.guide-manage-wrapper {
    display: inline-flex;
}
.guide-step {
    margin-bottom: 20px;
}
</style>
